package tests;

import common.IP;
import common.Utils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;

public class GameHall extends Utils {

    public static String url = "http://" + IP.ip + "/game_hall.html";

    public GameHall() {
        super(url);
    }

    //封装弹窗方法
    public void waitAlert(WebDriver driver){
        //显式等待弹窗的出现
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
        Alert alert = null;
        try {
            //检测弹窗的存在，存在会显式返回一个有效的alert对象
            alert = wait.until(ExpectedConditions.alertIsPresent());
            alert.accept();
        }catch (Exception e){
            System.out.println("GameRoomFail");
        }
    }
    //检测多个账号登录
    public void mulUser() {
        //检测到同个账号登录多次
        ((JavascriptExecutor) driver).executeScript("window.open('" + url + "');");
        // 切换到第二个标签页
        ArrayList<String> tabs = new ArrayList<>(driver.getWindowHandles());
        driver.switchTo().window(tabs.get(1)); // 切换到第二个标签页
        waitAlert(driver);
        driver.close();
        driver.switchTo().window(tabs.get(0));
    }

    //进行匹配对战
    public void match() throws IOException, InterruptedException {

        //点击开始匹配按钮
        driver.findElement(By.cssSelector("#match-button")).click();

    }
}
